//go:build windows

package collector

import (
	"os"
	"path/filepath"
	"sort"
	"strings"

	"sysinfo/internal/types"
)

// collectRecentFiles (Windows) 读取 APPDATA\Microsoft\Windows\Recent 下的 .lnk 文件
func collectRecentFiles(limit int) ([]types.RecentFile, error) {
	appdata := os.Getenv("APPDATA")
	if appdata == "" {
		return []types.RecentFile{}, nil
	}
	recentDir := filepath.Join(appdata, "Microsoft", "Windows", "Recent")
	entries, err := os.ReadDir(recentDir)
	if err != nil {
		return []types.RecentFile{}, nil
	}

	type rec struct {
		name    string
		path    string
		modTime int64
	}
	var list []rec

	for _, e := range entries {
		if e.IsDir() {
			continue
		}
		name := e.Name()
		if !strings.HasSuffix(strings.ToLower(name), ".lnk") {
			continue
		}
		info, err := e.Info()
		if err != nil {
			continue
		}
		list = append(list, rec{
			name:    name,
			path:    filepath.Join(recentDir, name),
			modTime: info.ModTime().UnixMilli(),
		})
	}

	sort.Slice(list, func(i, j int) bool { return list[i].modTime > list[j].modTime })
	if limit > 0 && len(list) > limit {
		list = list[:limit]
	}

	out := make([]types.RecentFile, 0, len(list))
	for _, it := range list {
		base := strings.TrimSuffix(it.name, filepath.Ext(it.name))
		out = append(out, types.RecentFile{
			Path:        it.path,
			DisplayName: base,
			OpenedTime:  fromMillis(it.modTime),
			Source:      "Windows Recent (.lnk)",
		})
	}
	return out, nil
}
